/**
 * @fileoverview 创建一个控制面板，管理HTML与CSS
 */
(function(){
	String.implement({
		//获取2个标记之间的字符串
		between : function(begin, end){
			var bp = this.indexOf(begin);
			if(bp == -1) return '';
			bp += begin.length;
			var ep = this.indexOf(end, bp);
			if(ep == -1) return '';
			return this.substr(bp, ep - bp);
		},
		//获取模板字符串
		getTpl : function(key){
			return this.between('<!--' + key , key + '-->').trim();
		}
	});

})();

(function(){
	
	var cssPreTags = {
		'firefox' : '-moz-',
		'chrome' : '-webkit-',
		'safari' : '-webkit-',
		'opera' : '-o-'
	};
	var csspre = cssPreTags[Browser.name] || '';
	
	Element.implement({
		//设置CSS3动画样式
		setCSS3Transition : function(csstext){
			this.setStyle(csspre + 'transition',  csstext.replace(/transform/gi, csspre + 'transform') );
			return this;
		}
	});
	
})();

(function(){
	var $empty = function(){};
	
	/**
	 * @class IframeTPL iframe 模板系统
	 */
	var IframeTPL = new Class({
		Implements : [Options, Events],
		options : {
		//	onReady : $empty,
			id : '',
			src : '',
			tplnames : []
		},
		initialize : function(options){
			this.setOptions(options);
			var ops = this.options, that = this;
			this.iframe = new Element('iframe[src="'+ops.src+'"]')
				.setStyle('display','none')
				.inject(document.body);
			this.iframe.addEvent('load',function(){
				var doc = that.iframe.contentWindow.document;
				var targetEl = doc.getElementById(ops.id);
				if(targetEl){
					that.parseHTML(targetEl.innerHTML);
				}
			});
		},
		//解析HTML模板字符串
		parseHTML : function(strTPL){
			var ops = this.options, cache = {};
			this.strTPL = strTPL;
			ops.tplnames.each(function(name){
				cache[name] = strTPL.getTpl('TPL.'+name);
			},this);
			this.fireEvent('ready', [cache]);
		}
	});
	
	this.IframeTPL = IframeTPL;
	
	/**
	 * @class ConfigPannel 控制面板类
	 */
	 
	//HTML模板
	var TPL = {};

	//基类
	var PannelBase = new Class({
		Implements : [Options,Events],
		options : {
			nodetype : 'nodetype'	
		},
		initialize : function(options){
			this.setOptions(options);
			this.nodes = {};
			this.build(this.options);
		},
		//解析节点
		parseNodes : function(){
			if(!this.root){return;}
			var prop = this.options.nodetype;
			this.root.getElements('['+prop+']').each(function(el){
				var elem = new Element(el);
				this.nodes[elem.get(prop)] = elem;
			}, this);
		},
		build : $empty
	});

	//滑动条
	var PannelSlider = new Class({
		Extends : PannelBase,
		options : {
			title : '',		//标题
			method : '',	//方式['style',prop]
			prop : '',		//属性['width','class','height' ...]
			target : '',	//操作目标选择器
			type : '',		//类型['range','select']
			val : [],		//值域
			format : function(val){	//格式化数据
				return val;
			},
			target : null	//要操作的元素
		},
		build : function(ops){
			this.target = ops.target;
			if(!this.target){return;}
			this.root = new Element('li[class="item"]');
			var data = {
				'title' : ops.title,
				'desc' : ops.desc,
				'min' : ops.val[0],
				'max' : ops.val[1] < ops.val[0] ? ops.val[0] : ops.val[1],
				'value' : ops.value || '',
				'step' : ops.step || ''
			}
			this.root.set('html', TPL.SLIDER.substitute(data)).inject(ops.root);
			this.parseNodes();
			this.nodes.knob.setCSS3Transition('top 0.3s ease-out 0s, background-color 0.3s ease-out 0s')
			
			this.bound = {
				update : this.update.bind(this),
				setRange : this.setRange.bind(this),
				showKnob : this.showKnob.bind(this),
				hideKnob : this.hideKnob.bind(this)
			};
			this.attach();
			
			val = this.target[ops.method === 'style' ? 'getStyle' : 'get'](ops.prop);
			val = val.toInt().limit(data.min, data.max);
			this.nodes.slider.set('value', val);
				
			this.update();
		},
		
		//绑定事件
		attach : function(){
			this.nodes.min.addEvent('change',this.bound.setRange);
			this.nodes.max.addEvent('change',this.bound.setRange);
			this.nodes.knob.addEvents({
				'mouseenter' : this.bound.showKnob,
				'mouseleave' : this.bound.hideKnob
			});
			this.nodes.slider.addEvents({
				'change' : this.bound.update,
				'mouseenter' : this.bound.showKnob,
				'mouseleave' : this.bound.hideKnob
			});
		},
		
		//更新范围
		setRange : function(){
			var minval = this.nodes.min.get('value').toInt(10);
			var maxval = this.nodes.max.get('value').toInt(10);
			maxval = maxval < minval ? minval : maxval;
			this.nodes.max.set('value', maxval);
			var val = this.nodes.slider.get('value').toInt(10);
			this.nodes.slider.set({
				'min' : minval,
				'max' : maxval,
				'value' : val.limit(minval, maxval)
			});
			this.update();
		},
		
		//更新目标数据
		update : function(){
			var val = this.nodes.slider.get('value'), ops = this.options;
			val = ops.format(val);
			this.nodes.slider.set('title', val);
			this.nodes.knob.set('html', val);
			if(ops.method === 'style'){
				this.target.setStyle(ops.prop, val);
			}else{
				this.target.set(ops.prop, val);
			}
		},
		//显示滑块值
		showKnob : function(){
			this.nodes.knob.setStyles({
				'background-color':'#65250F',
				'top':'-15px'
			});
		},
		//隐藏滑块值
		hideKnob : function(){
			this.nodes.knob.setStyles({
				'background-color':'#E55322',
				'top':'4px'
			});
		}
	});
	
	//选择器
	var PannelSelector = new Class({
		Extends : PannelBase,
		options : {
			title : '',		//标题
			method : '',	//方式['style','prop']
			prop : '',		//属性['width','class','height' ...]
			target : '',	//操作目标选择器
			type : '',		//类型['range','select']
			val : [],		//值域
			format : function(val){	//格式化数据
				return val;
			},
			target : null	//要操作的元素	
		},
		build : function(ops){
			this.target = ops.target;
			if(!this.target){return;}
			this.root = new Element('li[class="item"]');
			
			var data = {
				'title' : ops.title,
				'desc' : ops.desc
			}
			this.root.set('html', TPL.SELECTOR.substitute(data)).inject(ops.root);
			this.parseNodes();
			ops.val.each(function(val){
				this.nodes.selector.options.add(new Option(val,val));
			}, this);
			
			this.bound = {
				update : this.update.bind(this)
			};
			this.attach();
			this.update();
		},
		
		//绑定事件
		attach : function(){
			this.nodes.selector.addEvent('change', this.bound.update);
		},
		
		//更新元素
		update : function(){
			var val = this.nodes.selector.get('value'), ops = this.options;
			val = ops.format(val);
			if(ops.method === 'style'){
				this.target.setStyle(ops.prop, val);
			}else{
				this.target.set(ops.prop, val);
			}
		}
	});
	
	//设置面板
	var ConfigPannel = new Class({
		Extends : PannelBase,
		options : {
			id : 'demo'
		},
		build : function(ops){
			this.target = $(ops.id);
			if(!this.target){return;}
			this.root = new Element('div[class="conf confminisize"][style="width:15px; height:15px;"]');
			this.root.set('html', TPL.PANNEL.substitute({
				title : ops.id
			}));
			this.parseNodes();
			this.nodes.handle.set('title',ops.id);
			this.root.inject(document.body);
			this.setPos();
			
			this.bound = {
				toggle : this.toggle.bind(this)
			};

			this.attach();
			
			this.items = [];
			this.addItems(ops.items);
		},
		//绑定事件
		attach : function(){
			this.root.makeDraggable({
				handle : this.nodes.handle,
				onBeforeStart : function(){
					this.draged = false;
				}.bind(this),
				onDrag : function(){
					this.draged = true;
				}.bind(this)
			});
			this.nodes.minisize.addEvent('click',this.bound.toggle);
		},
		
		//设置位置
		setPos : function(){
			var pos = this.target.getPosition();
			var size = this.target.getSize();
			this.root.setStyles({
				'position':'absolute',
				'left' : pos.x + size.x - 8 + 'px',
				'top' : pos.y - 8 + 'px'
			});
		},
		
		//检查大小
		checkSize : function(){
			if(this._checkSized){return;}
			this._checkSized = true;

			var contentHeight = this.nodes.content.scrollHeight;
			this.contentHeight = contentHeight.limit(0,273);
			this.nodes.content.setStyle('height',contentHeight+'px');
			
			var rootHeight = this.root.scrollHeight;
			this.rootHeight = rootHeight.limit(0,300);
		},
		
		//添加配置项
		addItems : function(items){
			items.each(function(itemops){
				itemops.target = this.target.getElement(itemops.target);
				itemops.root = this.nodes.list;
				var item = this['createitem_'+itemops.type](itemops);
				this.items.push(item);
			},this);
		},
		//创建滑动条组件
		createitem_range : function(ops){
			return new PannelSlider(ops);
		},
		//创建选择器组件
		createitem_select : function(ops){
			return new PannelSelector(ops);
		},
		//切换展开，收缩状态
		toggle : function(evt){
			this.checkSize();
			if(this.draged){return;}	//如果鼠标按下后，拖动了设置面板，则不进行展开收缩操作
			this[ this.showed ? 'hide' : 'show' ]();
		},
		//展开
		show : function(){
			this.root
				.setCSS3Transition('width 0.5s ease-out 0s, height 0.5s ease-out 0.5s')
				.setStyles({
					'width' : '500px',
					'height': this.rootHeight+'px'
				});
			this.nodes.minisize.set('html', '-');
			this.nodes.title.show();
			this.showed = true;
		},
		//收缩
		hide : function(){
			this.root
				.setCSS3Transition('height 0.5s ease-out 0s, width 0.5s ease-out 0.5s')
				.setStyles({
					'width' : '15px',
					'height': '15px'
				});
			this.nodes.minisize.set('html', '+');
			this.nodes.title.hide();
			this.showed = false;
		}
	});

	this.ConfigPannel = ConfigPannel;

	//注册模板准备完成后执行的函数
	var ConfigPannelPrepares = [];
	ConfigPannel.Ready = function(){
		Object.each(arguments, function(fn){
			if(typeOf(fn) === 'function'){
				ConfigPannelPrepares.push(fn);
			}
		})
	};
	
	
	window.addEvent('domready',function(){
		var version = '20110616';
		
		new Element('link[href="/test/liangdong/src/css/common/configpanel.css?version='+version+'"][type="text/css"][rel="stylesheet"]').inject(document.getElement('head'));

		//引入HTML模板
		new IframeTPL({
			src : '/test/liangdong/src/templete/configpannel.html?version='+version,
			id : 'tpl_configpannel',					//html模板容器ID
			tplnames : ['SLIDER','SELECTOR','PANNEL'],	//模板名称
			onReady : function(TPLS){					//模板引入完成后触发此事件
				TPL = TPLS;
				ConfigPannelPrepares.each(function(fn){
					fn();
				});
			}
		});
	});
	
})();